package workboard;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import workboard.WorkboardVo;

public class Workboard {

	// 첨부파일
	int fileSize = 10 * 1024 * 1024;
	String uploadPath = "C:\\Users\\jhta\\Desktop\\바탕하면 폴더\\123\\ColdEyes\\WebContent\\upload";
	String fileEncoding = "utf-8";

	// JDBC연결
	String driver = "oracle.jdbc.driver.OracleDriver";
	String url = "jdbc:oracle:thin:@192.168.10.108:1521:xe";
	String db_user = "hr";
	String db_pwd = "hr";

	Connection conn;
	WorkboardVo vo;


	// 페이지 분리 관련된 필드
	int listSize = 1; // 한페이지에 보여지는 행수
	int blockSize = 2; // 페이지 이동번호수

	int totSize = 0; // 검색된 데이타의 총 갯수
	int totPage = 0; // 전체 페이지수
	int totBlock = 0; // 전체 블럭수

	int nowPage = 1; // 현재 페이지
	int nowBlock = 1; // 현재 블럭

	int startNo = 0; // 목록의 시작 위치
	int endNo = 0; // 목록의 끝 위치
	int startPage = 0; // 현재 블럭의 시작 페이지번호
	int endPage = 0; // 현재 블럭의 끝 페이지번호

	public Workboard(){

		try {
			// 1)드라이버 로딩
			Class.forName(driver).newInstance();

			// 2)Connection 생성
			conn = DriverManager.getConnection(url, db_user, db_pwd);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// 페이지 분리 메서드
	public void computePage(){
		totPage = (int)Math.ceil(totSize*1.0 / listSize);
		totBlock = (int)Math.ceil(totPage*1.0 / blockSize);
		nowBlock = (int)Math.ceil(nowPage*1.0 / blockSize);

		endPage = nowBlock * blockSize;
		startPage = endPage - blockSize + 1;
		if(totPage < endPage) endPage = totPage;

		endNo = nowPage * listSize;
		startNo = endNo - listSize + 1;
		if(totSize < endNo) endNo = totSize;
	}

	public Vector<WorkboardVo> list() {

		Vector<WorkboardVo> v = new Vector<>();
		String sql = "";
		PreparedStatement ps;
		ResultSet rs;

		try {
			sql = "select count(*) from workboard where part = ?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, vo.getPart());
			
			rs = ps.executeQuery();
			rs.next();
			totSize = rs.getInt(1);
			
			computePage();
			
			sql = "select * from("
					+ "select rownum no, a.* from("
					+ "select * from workboard"
					+ " where part=? order by mdate desc)a )c left outer join workfile b on c.serial = b.fileid left outer join"
					+ " workfile2 ff on c.serial = ff.fileid2 where no between ? and ?";

			ps = conn.prepareStatement(sql);
			ps.setString(1, vo.getPart());
			ps.setInt(2, startNo);
			ps.setInt(3, endNo);
			rs = ps.executeQuery();

			while (rs.next()) {
				WorkboardVo bv = new WorkboardVo();
				bv.setPart(rs.getString("part"));
				bv.setSerial(rs.getInt("serial"));
				bv.setMid(rs.getString("mid"));
				bv.setSubject(rs.getString("subject"));
				bv.setMdate(rs.getDate("mdate"));
				bv.setContent(rs.getString("content"));
				bv.setFilename(rs.getString("filename"));
				bv.setFilename2(rs.getString("filename2"));
				v.add(bv);
			}

			rs.close();
			ps.close();
			conn.close();

		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return v;
	}

	public boolean insert(){

		boolean flag = false;

		/*		File f = new File(uploadPath);
		if(!f.exists())	f.mkdir();*/
		
		String str = vo.getRequest().getServletContext().getRealPath("WebContent");
		str = str.replace("\\WebContent", "");
		
		String pro = str.substring(str.lastIndexOf("\\") + 1, str.length());
		
		str = str.substring(0, str.indexOf(".")) + pro + "\\WebContent\\upload"; 
		setUploadPath(str);

		try{
			MultipartRequest mr = new MultipartRequest(vo.getRequest(), uploadPath, 
					fileSize, fileEncoding, new DefaultFileRenamePolicy()); // 객체가 만들어지는 순간 파일 업로드 된다.
			
			String part = mr.getParameter("part");
			String mid = mr.getParameter("mid");
			String subject = mr.getParameter("subject");
			String content = mr.getParameter("content");
			vo.setPart(part);

			//String orifile = mr.getOriginalFileName("filename");
			String sysfile = mr.getFilesystemName("filename");
			String sysfile2 = mr.getFilesystemName("filename2");

			// DB 저장
			String sql = "insert all " +
					"into workboard (serial, mid, subject, content, grp, deep,part)" +
					"values (seq_workboard.nextval, ?, ?, ?, seq_workboard.currval, seq_workboard.currval,?)";

			if (sysfile != null){
				sql += "into workfile (serial, fileid, filename) values " +
						"(seq_workfile.nextval, seq_workboard.currval, ?) "
						+ "into workfile2 (serial, fileid2, filename2) values "
						+ "(seq_workfile2.nextval, seq_workboard.currval, ?)";
			}

			sql += "select *from dual";	

			PreparedStatement pstmt = conn.prepareStatement(sql);

			pstmt.setString(1, mid);
			pstmt.setString(2, subject);
			pstmt.setString(3, content);
			pstmt.setString(4, part);

			if(sysfile != null){
				pstmt.setString(5, sysfile);
				pstmt.setString(6, sysfile2);
			}

			if (pstmt.executeUpdate() > 0) flag = true;

			pstmt.close();
			conn.close();


		}catch(Exception ex){
			ex.printStackTrace();
		}
		return flag;

	}

	public WorkboardVo view(){

		WorkboardVo m = null;
		String sql = null; 
		PreparedStatement ps = null;

		// 조회수 증가
		try{
			sql = "select b.*, f.filename,ff.filename2 from " +
					"((workboard b left outer join workfile f " +
					"on b.serial = f.fileid) left outer join workfile2 ff on b.serial=ff.fileid2) " +
					"where b.serial = ?";

			ps = conn.prepareStatement(sql);
			ps.setInt(1, vo.getSerial());

			ResultSet rs = ps.executeQuery();

			if(rs.next()){
				m = new WorkboardVo();
				m.setPart(rs.getString("part"));
				m.setSerial(rs.getInt("serial"));
				m.setMid(rs.getString("mid"));
				m.setSubject(rs.getString("subject"));
				m.setContent(rs.getString("content"));
				m.setMdate(rs.getDate("mdate"));
				m.setFilename(rs.getString("filename"));
				m.setFilename2(rs.getString("filename2"));
				
				m.setGrp(rs.getInt("grp"));
				m.setDeep(rs.getString("deep"));
			}

			rs.close();
			ps.close();
			conn.close();

		}catch(Exception ex){
			ex.printStackTrace();
		}

		return m;
	}

	public boolean modify(){
		boolean flag = false;
		try{
			// 첨부 파일이 있는 경우, brdfile 테이블에 업데이트 
			// 없는 경우, brdfile 테이블에 삽입
			
			String str = vo.getRequest().getServletContext().getRealPath("WebContent");
			str = str.replace("\\WebContent", "");
			
			String pro = str.substring(str.lastIndexOf("\\") + 1, str.length());
			
			str = str.substring(0, str.indexOf(".")) + pro + "\\WebContent\\upload"; 
			setUploadPath(str);

			MultipartRequest mr = 
					new MultipartRequest(
							vo.getRequest(), 
							uploadPath,
							fileSize,
							fileEncoding,
							new DefaultFileRenamePolicy()); // 객체가 만들어지는 순간 파일 업로드 된다.
			
			

			int serial = Integer.parseInt(mr.getParameter("serial"));
			vo.setSerial(serial); // serial setting

			String subject = mr.getParameter("subject");
			String content = mr.getParameter("content");
			String filename = mr.getParameter("filename"); // 기존 파일
			String filename2 = mr.getParameter("filename2");
			String fileDelFlag = mr.getParameter("fileDelFlag");
			String fileDelFlag2 = mr.getParameter("fileDelFlag2");// 파일 삭제 여부 
			String sysfile = mr.getFilesystemName("newfilename");
			String sysfile2 = mr.getFilesystemName("newfilename2");// 새 파일

			vo.setPart(mr.getParameter("part")); // part setting
			
			PreparedStatement pstmt = null;
			String sql = null;

			// fileDelFlag == del 이면, 기존 첨부 파일에 삭제 버튼 누른 상태
			// 기존 첨부된 파일을 삭제 
			if(fileDelFlag.equals("del")){
				fileDel(filename, serial);
			}
			if(fileDelFlag2.equals("del2")){
				fileDel2(filename2, serial);
			}

			conn.setAutoCommit(false); // 자동 커밋 방지

			sql = "update workboard set subject = ?, content = ?, mdate = sysdate " +
					"where serial = ?";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, subject);
			pstmt.setString(2, content);
			pstmt.setInt(3, serial);

			
			if (pstmt.executeUpdate() > 0) flag = true;

			if (sysfile != null && sysfile != ""){
				sql = "insert into workfile (serial, fileid, filename) " +
						"values (seq_workfile.nextval, ?, ?)";
				
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, serial);
				pstmt.setString(2, sysfile);

				if (pstmt.executeUpdate() > 0){
					conn.commit();
					flag = true;
				}
				else conn.rollback();
			}
			
			if (sysfile2 != null && sysfile2 != ""){
				sql = "insert into workfile2 (serial, fileid2, filename2) " +
						"values (seq_workfile2.nextval, ?, ?)";
				 
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, serial);
				pstmt.setString(2, sysfile2);

				if (pstmt.executeUpdate() > 0){
					conn.commit();
					flag = true;
				}
				else conn.rollback();
			}

			pstmt.close();
			conn.close();

		}catch(Exception ex){
			ex.printStackTrace();
		}
		
		System.out.println("part : " + vo.getPart());
		return flag;
	}

	public void fileDel(String filename, int serial){
		
		String sql = "delete from workfile where fileid = ? and filename = ?";
		try{
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, serial);
			pstmt.setString(2, filename);
			pstmt.executeUpdate();

			File file = new File(uploadPath + "/" + filename);
			if(file.exists()) file.delete(); // 해당 디렉토리에 파일이 존재하면, 삭제
			
			pstmt.close();

		}catch(Exception ex){
			ex.printStackTrace();
		}

	}
	
	public void fileDel2(String filename, int serial){
		
		String sql = "delete from workfile2 where fileid2 = ? and filename2 = ?";
		try{
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, serial);
			pstmt.setString(2, filename);
			pstmt.executeUpdate();

			File file = new File(uploadPath + "/" + filename);
			if(file.exists()) file.delete(); // 해당 디렉토리에 파일이 존재하면, 삭제
			
			pstmt.close();

		}catch(Exception ex){
			ex.printStackTrace();
		}

	}

	public boolean delete(){
		boolean flag = false;
		ResultSet rs = null;
		File file;
		String sql = "delete from workboard where serial = ?";
		try{
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, vo.getSerial());

			if(pstmt.executeUpdate() > 0){
				
				sql = "select * from workfile where fileid = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, vo.getSerial());
				
				rs = pstmt.executeQuery();
				if(rs.next()){
					sql = "delete from workfile where fileid = " + vo.getSerial(); 
					pstmt = conn.prepareStatement(sql);
					pstmt.executeUpdate();
				}
								
				sql = "select * from workfile2 where fileid2 = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, vo.getSerial());
				
				rs = pstmt.executeQuery();
				if(rs.next()){
					sql = "delete from workfile2 where fileid2 = " + vo.getSerial(); 
					pstmt = conn.prepareStatement(sql);
					pstmt.executeUpdate();
				}
				
				file = new File(uploadPath + "/" + vo.getFilename());
				if (file.exists()) file.delete(); // 파일이 존재하면 삭제
				else{} // 파일이 없을 경우, 보류
				
				file = new File(uploadPath + "/" + vo.getFilename2());
				if (file.exists()) file.delete(); // 파일이 존재하면 삭제
				else{} 
				
				flag = true;
			}

			pstmt.close();
			conn.close();

		}catch(Exception ex){
			ex.printStackTrace();
		}
		return flag;
	}


	public WorkboardVo getVo() {
		return vo;
	}

	public void setVo(WorkboardVo vo) {
		this.vo = vo;
	}

	public int getListSize() {
		return listSize;
	}

	public void setListSize(int listSize) {
		this.listSize = listSize;
	}

	public int getBlockSize() {
		return blockSize;
	}

	public void setBlockSize(int blockSize) {
		this.blockSize = blockSize;
	}

	public int getTotSize() {
		return totSize;
	}

	public void setTotSize(int totSize) {
		this.totSize = totSize;
	}

	public int getTotPage() {
		return totPage;
	}

	public void setTotPage(int totPage) {
		this.totPage = totPage;
	}

	public int getTotBlock() {
		return totBlock;
	}

	public void setTotBlock(int totBlock) {
		this.totBlock = totBlock;
	}

	public int getNowPage() {
		return nowPage;
	}

	public void setNowPage(int nowPage) {
		this.nowPage = nowPage;
	}

	public int getNowBlock() {
		return nowBlock;
	}

	public void setNowBlock(int nowBlock) {
		this.nowBlock = nowBlock;
	}

	public int getStartNo() {
		return startNo;
	}

	public void setStartNo(int startNo) {
		this.startNo = startNo;
	}

	public int getEndNo() {
		return endNo;
	}

	public void setEndNo(int endNo) {
		this.endNo = endNo;
	}

	public int getStartPage() {
		return startPage;
	}

	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}

	public int getEndPage() {
		return endPage;
	}

	public void setEndPage(int endPage) {
		this.endPage = endPage;
	}

	public String getUploadPath() {
		return uploadPath;
	}

	public void setUploadPath(String uploadPath) {
		this.uploadPath = uploadPath;
	}



}
